

//左移导出字段
function addExportField(id1,id2,id3,id4){

	  $('#'+id1+' option:selected').each(function () {
		  	var val = $(this).val(); //获取单个value
	         $("#"+id3+" option[value="+val+"]").appendTo('#'+id4);
	         
	  });
	  $('#'+id1+' option:selected').appendTo('#'+id2);

	  
}

//右移导出字段
function delExportField(id1,id2,id3,id4){
	$('#'+id2+' option:selected').each(function () {
	  	var val = $(this).val(); //获取单个value
         $("#"+id4+" option[value="+val+"]").appendTo('#'+id3);
         
  });
  $('#'+id2+' option:selected').appendTo('#'+id1);
}

//上移
function upMove(id1,id2){  
    var so = $("#"+id1+" option:selected");   
    
    if(so.get(0).index!=0){  
      so.each(function(){
    	 var val = $(this).val();
     	 var objectOption =  $("#"+id2+" option[value="+val+"]");
     	 objectOption.prev().before(objectOption);
         $(this).prev().before($(this));  
      });  
    }  
  }  
 
//下移
 function downMove(id1,id2){  
    var alloptions = $("#"+id1+" option");  
    var so = $("#"+id1+" option:selected");  
    
    if(so.get(so.length-1).index!=alloptions.length-1){  
      for(i=so.length-1;i>=0;i--)  
      {  
        var item = $(so.get(i));
        var objectOption =  $("#"+id2+" option[value="+item.val()+"]");
        objectOption.insertAfter(objectOption.next());
        item.insertAfter(item.next());  
      }  
    }  
  }

//导出字段集合
function addFields(templateCode,ready){
	var addFieldValue=$("#templateType").val();
	
	var dataUrl="";
	$("#ecportFields option").remove();
	$("#isImportFields option").remove();
	$("#ecportSelectedFields option").remove();
	$("#isImportSelectedFields option").remove();
	$("#ecportCostomFields option").remove();
	$("#isImportCostomFields option").remove();
	$("#ecportSelectedCostomFields option").remove();
	$("#isImportSelectedCostomFields option").remove();
	if(addFieldValue=="03"){
		dataUrl = contextRootPath + '/cimsCascade/queryListLoanDetailTemplateExportFields';
	}else{	
		dataUrl = contextRootPath + '/cimsCascade/queryListCreditDetailTemplateExportFields';
	}
	
	//creditEcportFields
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		success: function(results) {
			var result=results.data;
			var j;
			var resultLength = result.length - 1;
			for (j = 0; j <= resultLength; j++) {
				
				if(result[j].businessType==cimsConstant.COSTOM_EXPORT_TYPE){
					$('#ecportCostomFields').append("<option value='"+result[j].fieldName+"'>"+result[j].fieldExportName+"</option>");
					$('#isImportCostomFields').append("<option value='"+result[j].fieldName+"'>"+result[j].isImport+"</option>");
				}else{
					$('#ecportFields').append("<option value='"+result[j].fieldName+"'>"+result[j].fieldExportName+"</option>");
					$('#isImportFields').append("<option value='"+result[j].fieldName+"'>"+result[j].isImport+"</option>");
				}
				
			}
			
			if(addFieldValue!="08"){
				 $("#ecportFields option[value='redeemDate']").remove();
				 $("#isImportFields option[value='redeemDate']").remove();
				 $("#ecportFields option[value='dealMakeCreditorValue']").remove();
				 $("#isImportFields option[value='dealMakeCreditorValue']").remove();
				 $("#ecportFields option[value='dealThisMakeCreditorValue']").remove();
				 $("#isImportFields option[value='dealThisMakeCreditorValue']").remove();
				 
				 
				 
			}else if(addFieldValue=="08"){
				$("#ecportFields option[value='deliverDate']").remove();
				$("#isImportFields option[value='deliverDate']").remove();
				$("#ecportFields option[value='thisMakeCreditorValue']").remove();
				$("#isImportFields option[value='thisMakeCreditorValue']").remove();
				$("#ecportFields option[value='makeCreditorValue']").text("赎回价值");
				
			}
			if(addFieldValue!="02"){
				$("#ecportFields option[value='repaymentDateCalculation']").remove();
			}
			if(addFieldValue=="02"){
				$("#ecportFields option[value='makeCreditorValue']").text("受让价格");
			}
			
			if(addFieldValue=="10"){
				$("#ecportFields option[value='dealCreditorStatus']").remove();
				$("#isImportFields option[value='dealCreditorStatus']").remove();				
			}
			
			var name = $("#templateType option:selected").text();
			
			$("#exportName").text("选择"+name+"导出字段");
			/*if(addFieldValue==cimsConstant.CREDIT_EXPORT_TYPE){
				
				$("#exportName").text("选择债权导出字段");
			}else if(addFieldValue==cimsConstant.LOAN_EXPORT_TYPE){
				
				$("#exportName").text("选择贷款导出字段");
			}*/
			if(ready=="ready"){
				addSelectFields(templateCode);
			}
		}
	});
		
	
}

//导出已选中字段集合
function addSelectFields(obj){
	
	var dataUrl = contextRootPath + '/tCMmExcelDictionary/queryTCMmExcelDictionaryByTemplateCode';

	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:{"templateCode":obj},
		success: function(results) {
			var cloumCodes=results.data;
			//选中的code
			cloumCodesSelect(cloumCodes);
		}
	});
}


function cloumCodesSelect(cloumCodes){
	
	var data = cloumCodes.split(",");

	for(var i=0;i<data.length;i++){
		var dataval=data[i];
		//var val=$("#ecportFields option[value='"+dataval+"']"); 
		var code= $("#ecportFields option[value='"+dataval+"']").val();
		var customer= $("#ecportCostomFields option[value='"+dataval+"']").val();

		if(dataval==code){
			$("#ecportFields option[value="+dataval+"]").appendTo($("#ecportSelectedFields"));
			$("#isImportFields option[value="+dataval+"]").appendTo($("#isImportSelectedFields"));
			 
		}else if(dataval=customer){
			$("#ecportCostomFields option[value="+dataval+"]").appendTo($("#ecportSelectedCostomFields"));
			$("#isImportCostomFields option[value="+dataval+"]").appendTo($("#isImportSelectedCostomFields"));
		}
	}
}


//保存验证模板信息
function saveTest(model){
	
	 var cooperorg = $('#cooperorgCode').val();
	 var contract = $('#contractCode').val();
	 var templateCode = $('#templateCode').val();
	 var fileName = $('#fileName').val();
	 var templateType = $('#templateType').val();
	 var ecportSelectedFields = $('#ecportSelectedFields option').length;
	 var ecportSelectedCostomFields = $('#ecportSelectedCostomFields option').length;
	 var columnCode = "";
	 var columnName = "";
	 var isImports = "";
	 var value='';
	 
	 if(cooperorg==value||contract==value||templateCode==value||fileName==value||templateType==value){
		 alert("必填项不能为空，请检查。");
		 return false;
	 }
	 
	 if(ecportSelectedFields==0||ecportSelectedCostomFields==0){
		 alert("已导出字段不能为空！");
		 return false;
	 }
	 
	 if(templateType==01){
		 var transferId = $('#ecportSelectedFields option[value=transferId]').length;
		 var makeCreditorValue = $('#ecportSelectedFields option[value=makeCreditorValue]').length;
		 var thisMakeCreditorValue = $('#ecportSelectedFields option[value=thisMakeCreditorValue]').length;
		 var deliverDate = $('#ecportSelectedFields option[value=deliverDate]').length;
		 var dealCreditorStatus = $('#ecportSelectedFields option[value=dealCreditorStatus]').length;
		 var creditCode = $('#ecportSelectedFields option[value=creditCode]').length;
		 var packageNum = $('#ecportSelectedFields option[value=packageNum]').length;
		 var cooperorgPackageName = $('#ecportSelectedFields option[value=cooperorgPackageName]').length;
		 
		 if(transferId==0||makeCreditorValue==0||thisMakeCreditorValue==0||deliverDate==0||dealCreditorStatus==0||creditCode==0){
			 alert("转让编号，债权编号，本次转让债权价值，转让债权价值，交割日期，交互状态为必选字段！");
			 return;
		 }else if(cooperorg==cimsConstant.TBJ_COOPERORG_CODE){
			 
			 if(cooperorgPackageName==0||packageNum==0){
				 alert("所属包编号和机构理财包为必选字段！");
				 return;
			 }
		 }
	 }
	 
		var contractCode = contract;
		if(model=='update'){
    		 saveTemplate(model); 
    	}else{
    		 $.ajax({
    	         type:"get",
    	         dataType: 'json',
    	         url:contextRootPath+"/tCMmExcelTemplate/isTCMmExcelTemplate",
    	         data:{
    	        	 "contractCode":contractCode,
    	        	 "templateType":templateType,
    	        	 "templateCode":templateCode
    	         },
    	         success:function(msg){
    	        	 var msgData = msg.data;
    	         	var excelTemplate;
    	         	if(null==msgData){
    	         		excelTemplate=null;
    	         	}else{
    	         		excelTemplate = msgData.length;
    	         	}
    	         	var fileName = $('#fileName').val();	
    	         		 if(excelTemplate>=1){
    		        		 alert("该合约在在此应用场景已存在模板！或者模板编码重复！");
    		        		return;
    		        	 }else {
    		        		 saveTemplate(model); 
    		        	 }

    	         }
    	     });
    	}
		
 	 
}

//模板保存
function saveTemplate(model){
	
	 var id = $('#dtoid').val();
	 var cooperorg = $('#cooperorgCode').val();
	 var contract = $('#contractCode').val();
	 var templateCode = $('#templateCode').val();
	 var fileName = $('#fileName').val();
	 var templateType = $('#templateType').val();
	 var columnCode = "";
	 var columnName = "";
	 var isImports = "";
	 var columnCodeCostom = "";
	 var columnNameCostom = "";
	 var isImportsCostom = "";
	
	 $("#ecportSelectedFields option").each(function () {
         var txt = $(this).text(); //获取单个text
         var val = $(this).val(); //获取单个value
         
         columnCode += val + ",";
         
         columnName += txt + ",";
     });
     
     $("#isImportSelectedFields option").each(function () {
         var txt = $(this).text(); //获取单个value
         
         isImports += txt + ",";
         
     });
     
     $("#ecportSelectedCostomFields option").each(function () {
         var txt = $(this).text(); //获取单个text
         var val = $(this).val(); //获取单个value
         
         columnCodeCostom += val + ",";
         
         columnNameCostom += txt + ",";
     });
     
     $("#isImportSelectedCostomFields option").each(function () {
         var txt = $(this).text(); //获取单个value
         
         isImportsCostom += txt + ",";
         
     });
     
     columnCode += columnCodeCostom;
     
     columnName += columnNameCostom;
     
     isImports += isImportsCostom;
     
     columnCode = columnCode.substring(0, columnCode.length-1);
     
     columnName = columnName.substring(0, columnName.length-1);
     
     isImports = isImports.substring(0, isImports.length-1);
     
     var dataUrl = contextRootPath + '/cimsCascade/saveListTemplateExportFields';
    /* $("#templateSave").attr("disabled","disabled");
 	 $.ajax({
 		url: dataUrl,
 		type: 'post',
 		dataType: 'json',
 		data:{"cooperorgCode":cooperorg,
 			"contractCode":contract,
 			"templateCode":templateCode,
 			"fileName":fileName,
 			"templateType":templateType,
 			"columnCode":columnCode,
 			"columnName":columnName,
 			"isImports":isImports},
 		success: function(result) {
 			
 		}
 		
 	 });*/
 	 
 	if(model=='update'){
 		var params={"id":id,
 				"fileName":fileName,
	 			"templateCode":templateCode,
	 			"columnCode":columnCode,
	 			"columnName":columnName,
	 			"model":model,
	 			"isImports":isImports};
	 }else{
		 var params={"cooperorgCode":cooperorg,
		 			"contractCode":contract,
		 			"templateCode":templateCode,
		 			"fileName":fileName,
		 			"templateType":templateType,
		 			"columnCode":columnCode,
		 			"columnName":columnName,
		 			"model":model,
		 			"isImports":isImports};
		 	 
	 }
 	 
 	jyAjax(
 			dataUrl,
 			params,
 			function(msg){
 				alert("保存成功！");
 	  	});
}

//确认导出
function sureExport(){
	var isDeleteAndIsExport = $("#isDeleteAndIsExport").val();
	if(false==isDeleteAndIsExport || "false"==isDeleteAndIsExport){
		alert("请先保存交易！");
		return;
	}
	
	var obj  = $('#contractCode').length;
	var valueContractCode;
	if(obj>0){
		valueContractCode = $('#contractCode').val();
	}else {
		valueContractCode = $('#dtocontractCode').val();
	}
	
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var dealCode = $('#dealCode').val();
	if(""==valueContractCode || null==valueContractCode){
		alert("请选择合约！");
		return;
	}
	var creditPackage = $('#dealPackage').val();
	
	var exportTypeValue ="" + $("#exportType").val();
	var fileName = $('#fileName').val();
	var dealType = $('#dealType').val();
	var exportType="";
	if("credit"==exportTypeValue){
		exportType="credit";
	/*	var url = contextRootPath+"/cimsCascade/isNotExportCredit";
		$.ajax({
	        type:"get",
	        dataType: 'json',
	        url:url,
	        data:{
	       	 "dealCode":dealCode
	        },
	        success:function(msg){
	        	isNotExport = msg.msg;
	        	if(isNotExport=="false"){
	        		alert("影像资料没有全部上传完毕！");
	        		return;
	        	}else{
	        		
	        	};
	        }
	    });*/
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}else if("loan"==exportTypeValue){
		exportType="loan";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}else if("redemption"==exportTypeValue){
		exportType="redemption";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}else if("buyBack"==exportTypeValue){
		exportType="buyBack";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}
	
	
}

//是否存在模板
function isNotTemplate(contractCode,templateType,url){
	
	$.ajax({
        type:"get",
        dataType: 'json',
        url:contextRootPath+"/tCMmExcelTemplate/queryListTCMmExcelTemplate",
        data:{
       	 "contractCode":contractCode,
       	 "templateType":templateType
        },
        success:function(msg){
        	var msgData = msg.data;
        	var excelTemplate;
        	if(null==msgData){
        		excelTemplate=null;
        	}else{
        		excelTemplate = msgData.length;
        	}
       	 if(null==excelTemplate||excelTemplate==0||excelTemplate>2){
       		alert("未设置导出模板！");
       		return;
       	 }else{
       		$("#saveDeal").hide();
       		$("#spanCode").hide();
       		$("#addCredit").hide();
       		$("#deleteCredit").hide();
       		$("#addLoan").hide();
       		$("#deleteLoan").hide();
       		 window.location = url;
       	 }
        }
    });
}


//债权导入
var dialog_import = null;
function importCreditDetailReally(loanType,resultType){
	var obj  = $('#cooperorgCode').length;
	var valueCooperorgCode;
	if(obj>0){
		valueCooperorgCode = $('#cooperorgCode').val();
	}else {
		valueCooperorgCode = $('#dtocooperorgCode').val();
	}
	var valueContractCode = $('#dtocontractCode').val();
	var dealCode = $('#dealCode').val();
	var importUrl = "cimsCascade/importCreditDetail";
	var importUrlLoan = "cimsCascade/importLoanDetail";
	var dealType = $('#dealType').val();
	var exportTypeValue ="" + $("#exportType").val();
	var dtoagreementCode = $('#dtoagreementCode').val();
	var creditPackageName = $('#dealPackage').val();
	var creditAffiliation = $("#creditAffiliation").val();
	
	if(loanType=="true"){
		importUrl = importUrlLoan;
	}else{
		if(creditAffiliation==null||creditAffiliation==""){
			alert("月还归属不能为空！");
			return ;
		}
	}
	var callBack = "";
	if(dealType=="08"||dealType=="01"){
		callBack = 'creditCallBack();'
	}else{
		callBack = 'loanCallBack();'
	}
	
		
	var dialogStruct={
		'display':contextRootPath+'/common/importExcelFile.jsp?contractCode=' + valueContractCode +
		'&dealCode='+dealCode+'&importUrl=' +importUrl + "&dealType=" + dealType + "&exportTypeValue=" + 
		 exportTypeValue + "&loan" + obj +"&resultType=" + resultType + "&agreementCode=" + dtoagreementCode + 
		 "&packageNum=" + creditPackageName + 
		 "&cooperorgCode=" + valueCooperorgCode+
		 "&creditAffiliation=" + creditAffiliation+
		 "&callBack="+callBack,
		'width':800,
		'height':400,
		'title':'导入数据',
		'isIframe':'true',
		'buttons':[{'text':'关闭','isClose':true}]
	};
	dialog_import =jyDialog(dialogStruct);
	dialog_import.open();
}


//债权转让结算台账导入  zhoupeng 2015-12-17
var dialog_import = null;
function importCreditSrttleBill(loanType,resultType){
	
	var importUrl = "cimsCascade/importCreditSettleBill";	
	var callBack = 'creditSettleBillBack()';
		
	var dialogStruct={
		'display':contextRootPath+'/common/importExcelFile.jsp?importUrl=' +importUrl + 
		 "&callBack="+callBack,
		'width':800,
		'height':400,
		'title':'导入数据',
		'isIframe':'true',
		'buttons':[{'text':'关闭','isClose':true}]
	};
	dialog_import =jyDialog(dialogStruct);
	dialog_import.open();
}

function creditSettleBillBack(){
	//查询修改后的数据
	queryData();
	return "处理成功";
}

function creditCallBack(){
	//加载债权信息
	initFnCreditDetailView();
	$("#creditDetailTable").show();
	$("#creditAffiliation").attr("disabled","disabled");
	CreditValueSum();
	return "处理成功";
}

function loanCallBack(){
	return "处理成功";
}
//导入模板验证
function importCreditDetail(obj,resultType){
	
	var contractCode = $('#dtocontractCode').val();
	var templateType = $('#dealType').val();
	
	$.ajax({
        type:"get",
        dataType: 'json',
        url:contextRootPath+"/tCMmExcelTemplate/queryListTCMmExcelTemplate",
        data:{
       	 "contractCode":contractCode,
       	 "templateType":templateType
        },
        success:function(msg){
        	var msgData = msg.data;
        	var excelTemplate;
        	if(null==msgData){
        		excelTemplate=null;
        	}else{
        		excelTemplate = msgData.length;
        	}
       	 if(null==excelTemplate||excelTemplate==0||excelTemplate>2){
       		alert("未设置模板！");
       		return;
       	 }else{
       		importCreditDetailReally(obj,resultType);
       	 }
        }
    });
}

function downLoadLoan(){
	var dealCode = $('#dealCode').val();
	var url = contextRootPath + '/export/exportImageZip?dealCode='+dealCode;
	$('#downFrameId').attr("src", url);
	// window.location=url; 
}

//合作机构导入公共方法以及导入模板验证
function publicImportMothed(contractCode,dealType,dataPath,className,packageNum,callBack){
	
	$.ajax({
		async: false,
        type:"get",
        dataType: 'json',
        url:contextRootPath+"/tCMmExcelTemplate/queryListTCMmExcelTemplate",
        data:{
       	 "contractCode":contractCode,
       	 "templateType":dealType
        },
        success:function(msg){
        	var msgData = msg.data;
        	var excelTemplate;
        	if(null==msgData){
        		excelTemplate=null;
        	}else{
        		excelTemplate = msgData.length;
        	}
       	 if(null==excelTemplate||excelTemplate==0||excelTemplate>2){
       		alert("未设置模板！");
       		return;
       	 }else{
       		publicImportMothedReally(contractCode,dealType,dataPath,className,packageNum,callBack);
       	 }
        }
    });
}

//授让统一导入入口
var dialog_import = null;
function publicImportMothedReally(contractCode,dealType,dataPath,className,packageNum,callBack){

	var importUrl = "excelTools/ImportDataName";	

	var dialogStruct={
		'display':contextRootPath+'/common/publicImportExcelFile.jsp?contractCode=' + contractCode + 
		'&importUrl=' +importUrl + "&dealType=" + dealType+"&className=" + className + "&dataPath=" + dataPath +"&callBack=" +callBack +"&packageNum=" +packageNum,
		'width':800,
		'height':400,
		'title':'导入数据',
		'isIframe':'true',
		'buttons':[{'text':'关闭','isClose':true}]
	};
	dialog_import =jyDialog(dialogStruct);
	dialog_import.open();
}

//公平用查询债权包显示标签
function completePackage(selectOptions,selectID,updatePackageValue,type){
	$("#" + selectID).hide();
	$("#" + selectID).after("<div class='ui-widget'><input id='dealPackage' onkeyup='chkChinese(this)' class='ui-autocomplete-input;' autocomplete='off' style='width: 132px;height: 21px;'></div>");
	
	if(type=='update'){
		$("#dealPackage").val(updatePackageValue);
		$("#dealPackage").attr("disabled","disabled");
	}else{
		if(selectOptions.length>0){
			
			$( "#dealPackage").autocomplete({
			       source:selectOptions,
			       minLength: 0, 
			       delay: 300,
			       change:function(event, ui){
			    	   creditPackageOperation(this);
			       },
			       select:function(event, ui){
			    	   creditPackageOperation(ui.item);
			       }
			    }).focus(function () {
			                $(this).autocomplete("search");
			    });
		}
	}
	
	
}

//查询费用模板
function costParameters(param,updateValue,type){
	var url = contextRootPath + "/tCMmCostParam/queryListTCMmCostParam";
	var params={"validateState":"1"};
	if(type=='update'){
		$('#'+param).val(updateValue);
		$('#'+param).attr("disabled","disabled");
	}else{
		jyAjax(url,params,function(msg){
			
	    	var v_status = msg.status;
	    	//alert(v_status);
	    	if(v_status.indexOf('ok') >-1){
	    		var result=msg.data;
				var j;
				var resultLength = result.length - 1;
				$('#'+param).html("<option name='请选择' value='-1'>请选择</option>");
				for (j = 0; j <= resultLength; j++) {
					$('#'+param).append("<option name='"+result[j].costName+"' value='"+result[j].costCode+"'>"+result[j].costName+"</option>");
				}
	    		
	    	}else{
	    		alert(msg.msg);
	    	}
		});
	}
	
}



